<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>GEO散点</title>
    <link rel="stylesheet" href="../../css/main.css">
    <script src="../../mapData/js/jquery.min.js"></script>
    <script type="text/javascript" src="../../mapData/js/echarts/echarts.js"></script>
</head>
<body>
<div class="wrap" style="position: relative;">
    <div id="map" style="height: 940px;width: 100%;float: left"></div>
</div>
</body>
<script type="text/javascript">
    var geoCoordMap = {
        '娄烦县': [111.793798,38.066035],
        '古交市': [112.174353, 37.908534],
        '阳曲县': [112.673818,38.058797],
        '尖草坪区': [112.487122,37.939893],
        '万柏林区': [112.522258,37.862653],
        '晋源区': [112.477849,37.715619],
        '清徐县': [112.357961,37.60729],
        '杏花岭区': [112.560743,37.879291],
        '迎泽区': [112.558851,37.855804],
        '小店区': [112.564273,37.817974]};

    var barData = [
        ['娄烦县', randomValue(),randomValue(),randomValue()],
        ['古交市', randomValue(),randomValue(),randomValue()],
        ['阳曲县', randomValue(),randomValue(),randomValue()],
        ['尖草坪区', randomValue(),randomValue(),randomValue()],
        ['万柏林区', randomValue(),randomValue(),randomValue()],
        ['晋源区', randomValue(),randomValue(),randomValue()],
        ['清徐县', randomValue(),randomValue(),randomValue()],
        ['杏花岭区', randomValue(),randomValue(),randomValue()],
        ['迎泽区', randomValue(),randomValue(),randomValue()],
        ['小店区', randomValue(),randomValue(),randomValue()]
    ];

    // 产生随机数
    function randomValue() {
        return Math.round(Math.random()*1000000);
    }

    // 初始化echarts示例mapChart
    var mapChart = echarts.init(document.getElementById('map'));

    // 初始化地图数据
    function makeMapData(barData) {
        var mapData = [];
        for (var i = 0; i < barData.length; i++) {
            var geoCoord = geoCoordMap[barData[i][0]];
            if (geoCoord) {
                mapData.push({
                    name: barData[i][0],
                    value: geoCoord.concat(barData[i].slice(1))
                });
            }
        }
        return mapData;
    };

    // mapChart的配置
    var option = {
        animation: false,
        // 地图背景颜色
        backgroundColor: new echarts.graphic.RadialGradient(0.5, 0.5, 0.4, [{
            offset: 0,
            color: '#4b5769'
        }, {
            offset: 1,
            color: '#404a59'
        }]),
        title : {
            text: '太原市各区县人口柱状图',
            subtext:'',
            x:'center',
            textStyle : {
                color: '#fff'
            }
        },
        tooltip : {
            trigger: 'axis',
            formatter: '{b}'
        },
        toolbox: {
            show : true,
            orient : 'vertical',
            x: 'right',
            y: 'center',
            feature : {
                mark : {show: true},
                dataView : {show: true, readOnly: false},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        geo: {
            map: 'taiyuan',
            roam: true,// 允许缩放
            zoom: 1.155,// 默认缩放等级
            //center: [112.522258,37.862653], // 初始中心位置
            label: {
                emphasis: {
                    show: false,
                    areaColor: '#eee'
                }
            },
            // 地区块儿颜色
            itemStyle: {
                normal: {
                    areaColor: '#55C3FC',
                    borderColor: '#fff'
                },
                emphasis: {
                    areaColor: '#21AEF8'
                }
            }
        },
        series: []
    }

    function renderEachCity() {
        var option = {
            xAxis: [],
            yAxis: [],
            grid: [],
            series: []
        };
        echarts.util.each(barData, function(dataItem, idx) {
            var geoCoord = geoCoordMap[dataItem[0]];
            var coord = mapChart.convertToPixel('geo', geoCoord);
            idx += '';
            inflationData = [30,50,20];

            option.xAxis.push({
                id: idx,
                gridId: idx,
                type: 'category',
                name: dataItem[0],
                nameLocation: 'middle',
                nameGap: 3,
                splitLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    show: false
                },
                axisLine: {
                    onZero: false,
                    lineStyle: {
                        color: '#666'
                    }
                },
                data: ["数据A","数据B","数据C"],
                z: 100

            });
            option.yAxis.push({
                id: idx,
                gridId: idx,
                splitLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    show: false
                },
                axisLine: {
                    show: false,
                    lineStyle: {
                        color: '#1C70B6'
                    }
                },
                z: 100
            });
            option.grid.push({
                id: idx,
                width: 30,
                height: 40,
                left: coord[0] - 15,
                top: coord[1] - 15,
                z: 100
            });
            option.series.push({
                id: idx,
                type: 'bar',
                xAxisId: idx,
                yAxisId: idx,
                barGap: 0,
                barCategoryGap: 0,
                data: inflationData,
                z: 100,
                itemStyle: {
                    normal: {
                        color: function(params){
                            // 柱状图每根柱子颜色
                            var colorList = ['#F75D5D','#59ED4F','#4C91E7'];
                            return colorList[params.dataIndex];
                        }
                    }
                }
            });
        });
        console.time('a');
        mapChart.setOption(option);
        console.timeEnd('a');
    }
    setTimeout(renderEachCity, 0);

    // 缩放和拖拽
    function throttle(fn, delay, debounce) {

        var currCall;
        var lastCall = 0;
        var lastExec = 0;
        var timer = null;
        var diff;
        var scope;
        var args;

        delay = delay || 0;

        function exec() {
            lastExec = (new Date()).getTime();
            timer = null;
            fn.apply(scope, args || []);
        }

        var cb = function() {
            currCall = (new Date()).getTime();
            scope = this;
            args = arguments;
            diff = currCall - (debounce ? lastCall : lastExec) - delay;

            clearTimeout(timer);

            if (debounce) {
                timer = setTimeout(exec, delay);
            } else {
                if (diff >= 0) {
                    exec();
                } else {
                    timer = setTimeout(exec, -diff);
                }
            }

            lastCall = currCall;
        };

        return cb;
    }

    var throttledRenderEachCity = throttle(renderEachCity, 0);
    mapChart.on('geoRoam', throttledRenderEachCity);
    mapChart.setOption(option);

    // 点击显示柱状图
    mapChart.on('click',function(e){
        console.log(e)
        // console.log(params);
        if(e.componentSubType == "bar"){
            // 先清除所有柱状图
            $('.tongJiTu').remove();
            // 创建遮挡层
            creatWrap();
            // 创建柱状图容器
            var divObj = document.createElement('div');
            $(divObj).addClass('tongJiTu');
            divObj.id = 'zhuzhuang';
            divObj.title = e.name;
            var divX = getMousePos()['x'];
            var divY = getMousePos()['y'];
            $(divObj).css({
                'width': 250,
                'height': 180,
                'border': '1px solid #ccc',
                'position': 'absolute',
                'top': divY,
                'left': divX
            }).appendTo('.wrap');
            // 创建柱状图
            zhuZhuangTu();
            // 点击遮挡层消失
            clearWrap('.zhedang');
        }
        return;
    });
    // 获取横纵坐标
    function getMousePos(e) {
        var e = event || window.event;
        var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
        var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
        var x = e.pageX || e.clientX + scrollX;
        var y = e.pageY || e.clientY + scrollY;
        // console.log(x,y)
        return {'x': x,'y': y};
    }
    // 生成柱状图
    function zhuZhuangTu() {
        var zhuzhuang = echarts.init(document.getElementById('zhuzhuang'));
        option = {
            backgroundColor: 'rgba(255,255,255,.3)',
            legend: {
                data: ['数据A','数据B','数据C']
            },
            xAxis: [
                {

                    type: 'category',
                    data: ['数据A','数据B','数据C']
                }
            ],
            yAxis: [
                {
                    splitLine: {
                        show: false
                    },
                    type: 'value'
                }
            ],
            series: [
                {
                    type: 'bar',
                    itemStyle: {
                        normal: {
                            color: function(params){
                                var colorList = ['#F75D5D','#59ED4F','#4C91E7'];
                                return colorList[params.dataIndex];
                            },
                            label: {
                                show: true,
                                position: 'top',
                                textStyle: {
                                    color: '#000'
                                }
                            }
                        }
                    },
                    data: [10,20,30]
                }
            ]
        };
        zhuzhuang.setOption(option);
    }

    // 生成遮挡层
    function creatWrap(){
        var zheDang = document.createElement('div');
        $(zheDang).addClass('zhedang').css({
            width: '100%',
            height: '100%',
            position: 'absolute',
            top: 0,
            left: 0,
            backgroundColor: 'rgba(0,0,0,.2)'
        }).appendTo('.wrap');
    }
    // 去掉遮挡层
    function clearWrap(id){
        $(id).click(function(e){
            // console.log(this);
            this.remove();
            $('.tongJiTu').remove();
            return false;
        });
    }

    // 数据加载项，增强用户体验
    mapChart.showLoading();
    // 读取geo地图数据
    $.get('../../mapData/map/json/shanxi/taiyuan.json', function (json)
    {
        echarts.registerMap('taiyuan', json); // 注册地图
        // 数据加载项，增强用户体验
        mapChart.hideLoading();
    });
</script>
</html>